package cn.by.wms.service;
import cn.by.wms.dao.InventoryBatchDao;
import cn.by.wms.dao.InventoryDao;
import cn.by.wms.dao.OutItemDao;
import cn.by.wms.dto.InventoryOptionDTO;
import cn.by.wms.entity.*;
import cn.hutool.core.util.ObjectUtil;
import cn.smart.core.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("out")
public class OutInventoryOptionServiceImpl implements IInventoryOptionService {
    @Autowired
    private OutItemDao outItemDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private InventoryBatchDao inventoryBatchDao;

    @Override
    public void process(InventoryOptionDTO dto) {

        //获取出库的outId
        String outId = dto.getRefId();
        //查询当前outId的所有商品
        OutItemQuery outItemQuery = new OutItemQuery().setOutId(outId);
        List<OutItem> outItems = outItemDao.select(outItemQuery);
        //遍历商品进行库存操作
        outItems.forEach(outItem -> {
            //循环开始
            //通过当前商品的ID在库存中查询
            InventoryQuery query = new InventoryQuery().setId(outItem.getProductId());
            List<Inventory> inventoryList = inventoryDao.select(query);
            //如果库存中没有该商品，则直接抛出异常
            if (ObjectUtil.isEmpty(inventoryList)) {
                BizException.throwBizException(452, "出库异常，库存中没有该商品");
            } else {
                Inventory inventory = inventoryList.get(0);
                //如果库存中有该商品，则直接更新数量即可
                Integer i = inventoryDao.updateQty(outItem.getQty() * (-1), inventory.getId(), inventory.getVersion());
                if (i == 0) {
                    BizException.throwBizException(453, "库存更新失败");
                }
            }
            //如果批次不存在，则直接插入
            //拿到当前商品的批次
            String batchId = outItem.getBatchId();
            //在批次表中查询这个批次是否存在
            InventoryBatchQuery batchQuery = new InventoryBatchQuery().setBatchId(batchId);
            List<InventoryBatch> inventoryBatches = inventoryBatchDao.select(batchQuery);
            if (ObjectUtil.isEmpty(inventoryBatches)){
                BizException.throwBizException(454, "批次不存在");
            }else {
                InventoryBatch inventoryBatch = inventoryBatches.get(0);
                //如果批次存在，则直接更新
                Integer i = inventoryBatchDao.updateQty(outItem.getQty()*(-1), inventoryBatch.getBatchId(), inventoryBatch.getVersion());
                if (i == 0) {
                    BizException.throwBizException(454, "批次更新失败");
                }
            }
        });

    }
}
